﻿using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using KMF.Common;
using KMF.DAL;
using KMF.WebUI.Areas.KMFadmin.Models;
using KMF.WebUI.Areas.KMFadmin.Attributes;

namespace KMF.WebUI.Areas.KMFadmin.Controllers
{
     [AdminLoggedAuthorize]
    public class AdminConfigController : Controller
    {
        //
        // GET: /Config/

        public ActionResult Index(int currentPage = 1)
        {
            int totalPage = 0;
            int itemsPerPage = int.Parse(ConfigurationManager.AppSettings["DefaultItemsPerPage"]);
            var model = ConfigDb.GetAllPaging(currentPage, itemsPerPage, ref totalPage) ?? new List<ViewConfigPagingDto>();
            ViewBag.PageInfo = new PageInfo {CurrentPage = currentPage, PageSize = itemsPerPage, TotalPages = totalPage};
            return View(model);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(ConfigDto model)
        {
            var result = ConfigDb.Add(model);
            if (result > 0) return RedirectToAction("Edit", new {configId = result});
            ModelState.AddModelError("ErrorSummary","Đã có lỗi xảy ra!");
            return View(model);
        }

        public ActionResult Edit(int configId)
        {
            var model = ConfigDb.GetById(configId) ?? new ConfigDto();
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ConfigDto model)
        {
            var result = ConfigDb.Update(model);
            if (result > 0) return View(model);
            ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
            return View(model);
        }

        public JsonResult Delete(int configId)
        {
            var result = ConfigDb.Delete(configId);
            return Json(result > 0, JsonRequestBehavior.AllowGet);
        }
    }
}
